package com.thanhnx.tlg1;

import java.util.ArrayList;

import model.OnBottomHit;


import android.content.Context;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import android.widget.ScrollView;

public class LinkScrollView extends ScrollView {
	public boolean cascadeScroll = true;
	private OnBottomHit listener;
	public ArrayList<LinkScrollView> others = new ArrayList<LinkScrollView>();

	public LinkScrollView(Context context) {
		super(context);
	}

	public LinkScrollView(Context context, AttributeSet attrs) {
		super(context, attrs);
	}

	public void setListener(OnBottomHit listener) {
		this.listener = listener;
	}

	@Override
	protected void onScrollChanged(int l, int t, int oldl, int oldt) {
		super.onScrollChanged(l, t, oldl, oldt);

		if (cascadeScroll) {
			for (int i = 0; i < others.size(); i++) {
				others.get(i).cascadeScroll = false;
				others.get(i).scrollTo(l, t);
				others.get(i).cascadeScroll = true;
			}
		}
		if (listener != null) {
			hitBottom(l, t, oldl, oldt);
		}
	}

	protected void hitBottom(int l, int t, int oldl, int oldt) {
		// Grab the last child placed in the ScrollView, we need it to
		// determinate the bottom position.
		View view = (View) getChildAt(getChildCount() - 1);
		// Calculate the scrolldiff
		int diff = (view.getBottom() - (getHeight() + getScrollY()));
		// if diff is zero, then the bottom has been reached
		if (diff == 0) {
			// notify that we have reached the bottom
			Log.d("", "MyScrollView: Bottom has been reached");
			// Add more button
			listener.bottomHit();
		}
	}

	private void addLoadMoreButton() {
		// final Button bt = new Button(MainActivity.this);
		// bt.setText("Load more row");
		// RelativeLayout.LayoutParams rl = new RelativeLayout.LayoutParams(
		// LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
		// rl.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
		// bt.setOnClickListener(new View.OnClickListener() {
		// @Override
		// public void onClick(View v) {
		// // rl_root.removeViewAt(rl_root.getChildCount()-1);
		// rl_root.removeView(bt);
		// }
		// });
		// bt.setLayoutParams(rl);
		// rl_root.addView(bt);
	}
}
